package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
* @author 作者 linweiqiang
* @version 创建时间：2017年11月14日 下午5:15:31
* 类说明
*/
public class ByteTFFile {
	
	
	/**
	 * 将byte转成文件
	 * @param imgByte
	 * @param path
	 * @return
	 */
	public static boolean byte2File(byte[] imgByte,String path){
		OutputStream out = null;
		try {
			out = new FileOutputStream(path);
			out.write(imgByte);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally {
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}
	
	/**
	 * 将文件转成byte
	 * @param fileStr
	 * @return
	 */
	public static byte[] file2Byte(String fileStr){
		File file = new File(fileStr);
		try {
			return ByteTFInputStream.input2Byte(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
     * 根据文件流判断图片类型
     * @param fis
     * @return jpg/png/gif/bmp
     */
	public static String getImgType(byte[] b){
		byte[] btype = new byte[4];
		for (int i = 0; i < btype.length; i++) {
			btype[i] = b[i];
		}
		String type = bytesToHexString(btype).toUpperCase();
        if (type.contains("FFD8FF")) {
            return "jpeg";
        } else if (type.contains("89504E47")) {
            return "png";
        } else if (type.contains("47494638")) {
            return "gif";
        } else if (type.contains("424D")) {
            return "bmp";
        }else{
            return "unknow";
        }
	}
	
	/**
     * byte数组转换成16进制字符串
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src){    
           StringBuilder stringBuilder = new StringBuilder();    
           if (src == null || src.length <= 0) {    
               return null;    
           }    
           for (int i = 0; i < src.length; i++) {    
               int v = src[i] & 0xFF;    
               String hv = Integer.toHexString(v);    
               if (hv.length() < 2) {    
                   stringBuilder.append(0);    
               }    
               stringBuilder.append(hv);    
           }    
           return stringBuilder.toString();    
       }
}
